package com.jiesen.base.modules.certificate.textbook.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jiesen.base.modules.certificate.textbook.model.TextBook;
import com.jiesen.base.modules.certificate.textbook.service.TextbookService;
import com.jiesen.base.utils.R;
import com.jiesen.base.utils.TreeUtil;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bao
 */

@RestController
@RequestMapping(value = "/textbook", produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
public class TestBookController {

	@Autowired
	private TextbookService textbookService;

	//根据条件获取证书list
	@RequestMapping("/getList")
	public R getList(TextBook video) {
		List<TextBook> list1 = textbookService.list1(video);
        JSONArray a = TreeUtil.listToTree(JSONArray.parseArray(JSON.toJSONString(list1)), "id", "parentId", "child");
		return R.ok().put("data", a);
	}

	//增加一个证书文件夹
    @RequestMapping(value = "/create",method = RequestMethod.POST)
	public R addVideo(@RequestBody TextBook textbook) {
		QueryWrapper<TextBook> queryWrapper =  new QueryWrapper<>();
		TextBook video = new TextBook();
		video.setParentId(textbook.getParentId());
		queryWrapper.setEntity(video);
		queryWrapper.orderByDesc("sorts");
		if(textbookService.list(queryWrapper).size()==0) {
			textbook.setSorts(1);
		}else {
			TextBook video2 = textbookService.list(queryWrapper).get(0);
			textbook.setSorts(video2.getSorts()+1);
		}

		if (textbook.getParentId()==null) {
			textbook.setParentId(0);
		}

		textbookService.save(textbook);
		return R.ok().put("data",textbook);
	}

	//删除一个证书文件夹
	@RequestMapping("/delete")
	public R delVideo(String id) {
        boolean b = textbookService.removeById(id);
        return R.ok();
	}

	//修改一个证书文件夹
	@PostMapping("/edit")
	public R updVideo(@RequestBody TextBook textbook) {
		textbookService.updateById(textbook);
		return R.ok().put("data",textbook);
	}

	//根据父类id查询内容
	@GetMapping("/view")
    public R view(@RequestParam("parentId")Integer parentId){
        List<TextBook> textBooks = textbookService.getTextbookByParentId(parentId);
        if (textBooks==null||textBooks.size()==0){
            return R.error("没有信息");
        }
        return R.ok().put("data",textBooks);
    }

    //根据父类id查询所有其下的子课程与章节并返回json树状结构
    @GetMapping("/views")
    public R views(@RequestParam("id")Integer id){
        List<TextBook> textBooks = textbookService.getTextBookAndChildById(id);
        if(textBooks==null){
            return R.error("没有数据");
        }
        return R.ok().put("data",textBooks);
    }


}
